package ch.fusun.baron.basic.turntask;

import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.player.Player;
import ch.fusun.baron.player.api.PlayerService;
import ch.fusun.baron.printing.MessagingService;
import ch.fusun.baron.turn.TurnTask;

/**
 * @author dezanets
 * 
 */
public class IncreaseAgeTurnTask implements TurnTask {

	@Inject
	private transient PlayerService playerService;
	@Inject
	private transient MessagingService messageService;

	/**
	 * Kryo
	 */
	public IncreaseAgeTurnTask() {
	}

	@Override
	public void execute() {
		for (Player player : playerService.getAllPlayers()) {
			if (!player.isDead()) {
				if (calcSurvivalProbability(player.getAge()) < Math.random()) {
					player.setDead(true);
					messageService.addMessage(playerService
							.getUser(playerService.getDynasty(player)),
							player.getName()
									+ " of "
									+ playerService.getDynasty(player)
											.getName() + " died at the age of "
									+ player.getAge());
				} else {
					player.setAge(player.getAge() + 1);
				}
				playerService.updatePlayer(player);
			}
		}
	}

	private static double calcSurvivalProbability(int age) {
		if (age < 5) {
			return age / 4.0 + 0.5;
		}
		if (age < 30) {
			return 0.999;
		}
		return -(age - 100.0) / 35.0;
	}
}
